package com.qianhui.dao;

import com.qianhui.common.CM;
import com.qianhui.common.IResult;
import com.qianhui.pojo.Goods;
import com.qianhui.pojo.GoodsHistory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * A data access object (DAO) providing persistence and search support for Goods
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 *
 * @author MyEclipse Persistence Tools
 * @see com.qianhui.pojo.Goods
 */
public class GoodsDAO extends BaseHibernateDAO
{
    private static final Logger log = LoggerFactory.getLogger(GoodsDAO.class);
    // property constants
    public static final String GOODS_NAME = "goodsName";
    public static final String GOODS_TIPS = "goodsTips";
    public static final String GOODS_BRAND = "goodsBrand";
    public static final String GOODS_ITEM_ID = "goodsItemId";
    public static final String GOODS_PRICE = "goodsPrice";
    public static final String GOODS_ORIGINAL_PRICE = "goodsOriginalPrice";
    public static final String GOODS_MIN_BUY_NUMBER = "goodsMinBuyNumber";
    public static final String GOODS_INVENTORY_NUMBER = "goodsInventoryNumber";
    public static final String GOODS_SALES_NUMBER = "goodsSalesNumber";
    public static final String GOODS_COMMENT_NUMBER = "goodsCommentNumber";
    public static final String GOODS_COMMISSION = "goodsCommission";
    public static final String GOODS_DISCOUNT = "goodsDiscount";
    public static final String GOODS_MAIN_PIC = "goodsMainPic";
    public static final String GOODS_GALLERY = "goodsGallery";
    public static final String GOODS_DETAIL = "goodsDetail";
    public static final String GOODS_TYPE_ID = "goodsTypeId";
    public static final String GOODS_OPERATION_MODE = "goodsOperationMode";
    public static final String GOODS_STATUS = "goodsStatus";

    public Goods save(Goods transientInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().saveOrUpdate(transientInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return transientInstance;
    }

    public List<Goods> saveList(List<Goods> list)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            for (Goods temp : list)
            {
                getSession().saveOrUpdate(temp);
            }
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return list;
    }

    public int delete(Goods persistentInstance)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            getSession().delete(persistentInstance);
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return IResult.DELETE_EXCEPTION;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return IResult.DELETE_SUCCESS;
    }

    public Goods findById(java.lang.String id)
    {
        log.debug("getting Goods instance with id: " + id);
        try
        {
            Goods instance = (Goods) getSession().get("com.qianhui.pojo.Goods", id);
            return instance;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByProperty(String propertyName, Object value)
    {
        log.debug("finding Goods instance with property: " + propertyName + ", value: " + value);
        try
        {
            String queryString = "from Goods as model where model." + propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List findByGoodsName(Object goodsName)
    {
        return findByProperty(GOODS_NAME, goodsName);
    }

    public List findByGoodsTips(Object goodsTips)
    {
        return findByProperty(GOODS_TIPS, goodsTips);
    }

    public List findByGoodsBrand(Object goodsBrand)
    {
        return findByProperty(GOODS_BRAND, goodsBrand);
    }

    public List findByGoodsItemId(Object goodsItemId)
    {
        return findByProperty(GOODS_ITEM_ID, goodsItemId);
    }

    public List findByGoodsPrice(Object goodsPrice)
    {
        return findByProperty(GOODS_PRICE, goodsPrice);
    }

    public List findByGoodsOriginalPrice(Object goodsOriginalPrice)
    {
        return findByProperty(GOODS_ORIGINAL_PRICE, goodsOriginalPrice);
    }

    public List findByGoodsMinBuyNumber(Object goodsMinBuyNumber)
    {
        return findByProperty(GOODS_MIN_BUY_NUMBER, goodsMinBuyNumber);
    }

    public List findByGoodsInventoryNumber(Object goodsInventoryNumber)
    {
        return findByProperty(GOODS_INVENTORY_NUMBER, goodsInventoryNumber);
    }

    public List findByGoodsSalesNumber(Object goodsSalesNumber)
    {
        return findByProperty(GOODS_SALES_NUMBER, goodsSalesNumber);
    }

    public List findByGoodsCommentNumber(Object goodsCommentNumber)
    {
        return findByProperty(GOODS_COMMENT_NUMBER, goodsCommentNumber);
    }

    public List findByGoodsCommission(Object goodsCommission)
    {
        return findByProperty(GOODS_COMMISSION, goodsCommission);
    }

    public List findByGoodsDiscount(Object goodsDiscount)
    {
        return findByProperty(GOODS_DISCOUNT, goodsDiscount);
    }

    public List findByGoodsMainPic(Object goodsMainPic)
    {
        return findByProperty(GOODS_MAIN_PIC, goodsMainPic);
    }

    public List findByGoodsGallery(Object goodsGallery)
    {
        return findByProperty(GOODS_GALLERY, goodsGallery);
    }

    public List findByGoodsDetail(Object goodsDetail)
    {
        return findByProperty(GOODS_DETAIL, goodsDetail);
    }

    public List findByGoodsTypeId(Object goodsTypeId)
    {
        return findByProperty(GOODS_TYPE_ID, goodsTypeId);
    }

    public List findByGoodsOperationMode(Object goodsOperationMode)
    {
        return findByProperty(GOODS_OPERATION_MODE, goodsOperationMode);
    }

    public List findByGoodsStatus(Object goodsStatus)
    {
        return findByProperty(GOODS_STATUS, goodsStatus);
    }

    public List findAll()
    {
        log.debug("finding all Goods instances");
        try
        {
            String queryString = "from Goods";
            Query queryObject = getSession().createQuery(queryString);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByIndexAndPageSizeAndStatusAnd_tidAnd_keyword(int index, int pageSize, String status, String tid, String keyword)
    {
        try
        {
            String sql = "from Goods g where g.goodsStatus=:status :tidSql :kSql order by g.goodsUpdateTime desc";
            if (CM.validIsEmpty(tid) == true)
            {
                sql = sql.replace(":tidSql", " ");
            }
            else
            {
                sql = sql.replace(":tidSql", "and g.goodsTypeId in (:tid)");
            }
            if (CM.validIsEmpty(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "and (g.goodsId like :keyword or g.goodsName like :keyword or g.goodsTips like :keyword or g.goodsBrand like :keyword or g.goodsItemId like :keyword)");
            }
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);

            if (CM.validIsEmpty(tid) == false)
            {
                query.setParameterList("tid", CM.fromSomePictureSrcToOneList(tid));
            }
            if (CM.validIsEmpty(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getGoodsTotalCountByStatusAnd_tidAnd_keyword(String status, String tid, String keyword)
    {
        try
        {
            String sql = "select count(*) from Goods g where g.goodsStatus=:status :tidSql :kSql order by g.goodsUpdateTime desc";
            if (CM.validIsEmpty(tid) == true)
            {
                sql = sql.replace(":tidSql", " ");
            }
            else
            {
                sql = sql.replace(":tidSql", "and g.goodsTypeId in (:tid)");
            }
            if (CM.validIsEmpty(keyword) == true)
            {
                sql = sql.replace(":kSql", " ");
            }
            else
            {
                sql = sql.replace(":kSql", "and (g.goodsId like :keyword or g.goodsName like :keyword or g.goodsTips like :keyword or g.goodsBrand like :keyword or g.goodsItemId like :keyword)");
            }
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);

            if (CM.validIsEmpty(tid) == false)
            {
                query.setParameterList("tid", CM.fromSomePictureSrcToOneList(tid));
            }
            if (CM.validIsEmpty(keyword) == false)
            {
                query.setParameter("keyword", "%" + keyword + "%");
            }
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByIndexAndPageSizeAnd_tid(int index, int pageSize, String tid)
    {
        try
        {
            String sql = "from Goods g where g.goodsTypeId=:tid order by g.goodsUpdateTime desc";
            Query query = getSession().createQuery(sql);

            query.setParameter("tid", tid);
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getGoodsTotalCountByTid(String tid)
    {
        try
        {
            String sql = "select count(*) from Goods g where g.goodsTypeId=:tid";
            Query query = getSession().createQuery(sql);
            query.setParameter("tid", tid);

            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int do_goods_save_and_history(List<Goods> goodList, List<GoodsHistory> goodsHistoryList)
    {
        Transaction tx = null;
        try
        {
            tx = getSession().beginTransaction();
            for (Goods g : goodList)
            {
                getSession().saveOrUpdate(g);
            }
            for (GoodsHistory gh : goodsHistoryList)
            {
                getSession().saveOrUpdate(gh);
            }
            tx.commit();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            if (tx != null)
            {
                tx.rollback();
            }
            return IResult.UPDATE_EXCEPTION;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
        return IResult.UPDATE_SUCCESS;
    }

    public List findByIdList(List<String> idList)
    {
        try
        {
            String queryString = "from Goods as model where model.goodsId in (:idList)";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameterList("idList", idList);
            return queryObject.list();
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByIndexAndPageSizeAndStatusAndTypeIdListAndOrderBy(int index, int pageSize, String status, List<String> typeIdList, String orderByStr)
    {
        try
        {
            String sql = "from Goods g where g.goodsStatus=:status and g.goodsTypeId in (:typeIdList) order by :orderByStr desc";
            sql = sql.replaceAll(":orderByStr", orderByStr);
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);
            query.setParameterList("typeIdList", typeIdList);
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getGoodsTotalCountByStatusAndTypeIdListAndOrderBy(String status, List<String> typeIdList, String orderByStr)
    {
        try
        {
            String sql = "select count(*) from Goods g where g.goodsStatus=:status and g.goodsTypeId in (:typeIdList) order by :orderByStr desc";
            sql = sql.replaceAll(":orderByStr", orderByStr);
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);
            query.setParameterList("typeIdList", typeIdList);
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByIndexAndPageSizeAndStatusAndKeywordAndOrderBy(int index, int pageSize, String status, String keyword, String orderByStr)
    {
        try
        {
            String sql = "from Goods g where g.goodsStatus=:status and (g.goodsName like :keyword or g.goodsTips like :keyword or g.goodsBrand like :keyword or g.goodsItemId like :keyword) order by :orderByStr desc";
            sql = sql.replaceAll(":orderByStr", orderByStr);
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);
            query.setParameter("keyword", "%" + keyword + "%");
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getGoodsTotalCountByStatusAndKeywordAndOrderBy(String status, String keyword, String orderByStr)
    {
        try
        {
            String sql = "select count(*) from Goods g where g.goodsStatus=:status and (g.goodsName like :keyword or g.goodsTips like :keyword or g.goodsBrand like :keyword or g.goodsItemId like :keyword) order by :orderByStr desc";
            sql = sql.replaceAll(":orderByStr", orderByStr);
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);
            query.setParameter("keyword", "%" + keyword + "%");
            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByIndexAndPageSizeAndStatus(int index, int pageSize, String status)
    {
        try
        {
            String sql = "from Goods g where g.goodsStatus=:status order by g.goodsUpdateTime desc";
            Query query = getSession().createQuery(sql);
            query.setParameter("status", status);
            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public List getListByIndexAndPageSize(int index, int pageSize)
    {
        try
        {
            String sql = "from Goods g order by g.goodsUpdateTime desc";

            Query query = getSession().createQuery(sql);

            query.setFirstResult((index - 1) * pageSize);
            query.setMaxResults(pageSize);
            List tempList = query.list();
            if (tempList == null)
            {
                return null;
            }
            else
            {
                if (tempList.size() > 0)
                {
                    return tempList;
                }
                else
                {
                    return null;
                }
            }
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

    public int getGoodsTotalCount()
    {
        try
        {
            String sql = "select count(*) from Goods g";

            Query query = getSession().createQuery(sql);

            int num = ((Number) query.iterate().next()).intValue();
            return num;
        } catch (HibernateException e)
        {
            e.printStackTrace();
            return -1;
        } finally
        {
            if (getSession() != null && getSession().isOpen() == true)
            {
                getSession().close();
            }
        }
    }

}